import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import VueMacros from 'unplugin-vue-macros/vite';
import type { PluginOption } from 'vite';
import proxy from 'vite-plugin-http2-proxy';
import Mkcert from 'vite-plugin-mkcert';
import svgLoader from 'vite-svg-loader';
import { type ProConfig } from '../index';
import pwa from './pwa';
import { TOKEN_PROXY } from '../constants';
import type { ViteEnv } from '../utils';
import { resolveProxy } from '../utils';
import { autoComponents } from './autoComponents';
import autoImport from './autoImport';

import { configMockPlugin } from './mock';
import { unocss } from './unocss';

export async function configVitePlugins (root: string, viteEnv: ViteEnv, isBuild: boolean, proConfig?: ProConfig) {
  const {
    VITE_LEGACY,
    VITE_VUE_REACTIVITY_TRANSFORM = true,
    VITE_USE_MOCK,
    VITE_IS_UNI,
    VITE_USE_HTTPS = true,
    VITE_PROXY,
    VITE_USE_PWA,
    VITE_PUBLIC_PATH
  } = viteEnv;
  
  const _root = root.replace(/\\/g, '/');
  
  const { pwaCfg } = proConfig || { pages: {} };
  
  const vitePlugins: (PluginOption | PluginOption[])[] = [
    VueMacros(),
    vue({
      reactivityTransform: VITE_VUE_REACTIVITY_TRANSFORM
    }),
    svgLoader(),
    vueJsx(),
    unocss(),
    autoComponents(_root),
    autoImport(_root),
    VITE_USE_PWA ? pwa(pwaCfg, VITE_PUBLIC_PATH) : ''
  ];
  
  VITE_LEGACY && isBuild && !VITE_IS_UNI && vitePlugins.push(legacy());
  
  VITE_USE_MOCK && vitePlugins.push(configMockPlugin(isBuild));
  
  if (!isBuild) {
    
    if (VITE_USE_HTTPS) {
      vitePlugins.push(
        Mkcert({
          source: 'coding'
        }),
        
        proxy(resolveProxy(VITE_PROXY?.concat(TOKEN_PROXY)) as any)
      );
    }
  }
  
  return vitePlugins;
}
